"""健康检查API端点"""

from fastapi import APIRouter, Depends
from datetime import datetime

from app.core.config import settings
from app.models.response import HealthResponse
from app.services.text_detection import TextDetectionService
from app.utils.logger import get_logger

logger = get_logger("health_api")
router = APIRouter()


@router.get("/health", response_model=HealthResponse, summary="健康检查")
async def health_check():
    """
    健康检查接口
    
    返回服务的健康状态信息，包括：
    - 服务状态
    - 应用版本
    - 检查时间
    - 各项服务状态详情
    """
    try:
        logger.info("执行健康检查")
        
        # 检查检测服务状态
        detection_service = TextDetectionService()
        platforms_stats = detection_service.get_platform_statistics()
        
        services_status = {
            "detection_service": {
                "status": "healthy",
                "total_platforms": platforms_stats.get("total_platforms", 0),
                "available_platforms": platforms_stats.get("available_platforms", 0),
                "total_tasks": platforms_stats.get("total_tasks", 0)
            },
            "database": {
                "status": "healthy",  # 这里应该实际检查数据库连接
                "connection": "ok"
            },
            "redis": {
                "status": "healthy",  # 这里应该实际检查Redis连接
                "connection": "ok"
            }
        }
        
        # 检查整体服务状态
        overall_status = "healthy"
        for service_name, service_info in services_status.items():
            if service_info.get("status") != "healthy":
                overall_status = "unhealthy"
                break
        
        return HealthResponse(
            status=overall_status,
            version=settings.app_version,
            timestamp=datetime.now(),
            services=services_status
        )
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return HealthResponse(
            status="unhealthy",
            version=settings.app_version,
            timestamp=datetime.now(),
            services={
                "error": str(e)
            }
        )


@router.get("/health/detailed", summary="详细健康检查")
async def detailed_health_check():
    """
    详细健康检查接口
    
    返回更详细的服务状态信息，包括各个检测平台的具体状态
    """
    try:
        logger.info("执行详细健康检查")
        
        detection_service = TextDetectionService()
        platforms_info = detection_service.get_available_platforms()
        
        detailed_info = {
            "application": {
                "name": settings.app_name,
                "version": settings.app_version,
                "debug_mode": settings.debug,
                "api_version": settings.api_v1_str
            },
            "platforms": platforms_info,
            "system": {
                "timestamp": datetime.now().isoformat(),
                "uptime": "N/A",  # 这里可以实际计算运行时间
                "memory_usage": "N/A"  # 这里可以实际获取内存使用情况
            }
        }
        
        return {
            "status": "healthy",
            "data": detailed_info
        }
        
    except Exception as e:
        logger.error(f"详细健康检查失败: {e}")
        return {
            "status": "error",
            "error": str(e)
        }


@router.get("/health/platforms", summary="检测平台状态")
async def platforms_health():
    """
    检测平台健康状态
    
    返回所有已配置检测平台的连接状态和基本信息
    """
    try:
        logger.info("检查检测平台状态")
        
        detection_service = TextDetectionService()
        platforms_info = detection_service.get_available_platforms()
        
        platform_status = {
            "total_configured": len(platforms_info),
            "available_count": sum(1 for p in platforms_info if p.get("is_available", False)),
            "platforms": platforms_info
        }
        
        return {
            "status": "ok",
            "data": platform_status
        }
        
    except Exception as e:
        logger.error(f"检查平台状态失败: {e}")
        return {
            "status": "error",
            "error": str(e),
            "data": {
                "total_configured": 0,
                "available_count": 0,
                "platforms": []
            }
        } 